package com.cirkana;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;

import com.cirkana.serial.SerializablePassData;
import com.cirkana.serial.SerializationException;
import com.cirkana.serial.SerializationUtil;

public class CirkanaActivity extends Activity {

	public static final int RESULT_CANCEL = -1;

	private static final String DATA_KEY = "data";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Global.setCurrentActivity(this);
		setResult(RESULT_CANCEL);
	}

	@SuppressWarnings("unchecked")
	protected SerializablePassData getRequest(Class type) {
		try {
			return getPassData(getIntent(), type);
		} catch (SerializationException e) {
			showErrorMessage(e);
			finish();
			return null;
		}
	}

	protected void setResponse(int resultCode, SerializablePassData data)
			throws SerializationException {
		Intent result = new Intent();
		setPassData(result, data);
		super.setResult(resultCode, result);
	}

	@SuppressWarnings("unchecked")
	protected SerializablePassData getResponse(Intent resultData, Class type)
			throws SerializationException {
		return getPassData(resultData, type);
	}

	@SuppressWarnings("unchecked")
	protected void startActivityForResult(Class type, int requestCode,
			SerializablePassData passData) throws SerializationException {
		Intent intent = new Intent(this, type);
		setPassData(intent, passData);
		super.startActivityForResult(intent, requestCode);
	}

	protected void showErrorMessage(Exception e) {
		openMessageBox("Error", e.getMessage());
	}

	protected void openMessageBox(String title, String message) {
		AlertDialog alertDialog;
		alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle(title);
		alertDialog.setMessage(message);
		alertDialog.show();
	}

	@SuppressWarnings("unchecked")
	private static SerializablePassData getPassData(Intent intent, Class type)
			throws SerializationException {
		return (SerializablePassData) SerializationUtil.deserialize(intent
				.getExtras().getByteArray(DATA_KEY), type);
	}

	private static void setPassData(Intent intent, SerializablePassData data)
			throws SerializationException {
		intent.putExtra(DATA_KEY, SerializationUtil.serialize(data));
	}
}
